package ch.fhnw.apsi.db;

import java.sql.SQLException;

public final class DBManager {
  final static ThreadLocal<DB> db = new ThreadLocal<>();

  static DB createDB() throws SQLException {
    return new MySQLDB();
  }

  public synchronized static DB getDB() throws SQLException {
    DB _db = db.get();
    if (_db == null || !_db.isValid())
      try {
        db.set(_db = createDB());
      } catch (final SQLException e) {
        // ignore the first one...
        _db = null;
        try {
          DB.class.wait(100);
        } catch (final InterruptedException e2) {
          Thread.currentThread().interrupt();
          throw e;
        }
      }
    if (_db == null)
      // second try:
      db.set(_db = createDB());
    return _db;
  }
}
